<template>
  <div class="PurchaseRegister">
    <!-- 采购单基本信息表单 -->
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="PurchaseRegister-form">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="订单编号" prop="orderNo">
            <div class="PurchaseRegister-form-orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号"
                        class="PurchaseRegister-form-orderNo-input"/>
              <el-button type="primary" class="PurchaseRegister-form-orderNo-btn" @click="generateOrderNo">随机生成
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select
                v-model="form.supplierId"
                placeholder="请选择供应商"
                filterable
                clearable
                class="PurchaseRegister-form-input"
            >
              <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
                v-model="form.note"
                type="textarea"
                :rows="4"
                placeholder="可填写备注"
                class="PurchaseRegister-form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 已添加商品列表 -->
    <div class="PurchaseRegister-table">
      <!-- 操作栏（与表格同级） -->
      <div class="PurchaseRegister-table-toolbar">
        <el-button type="primary" @click="openSelectProduct">添加商品</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>

      <el-table :data="items" class="PurchaseRegister-table-main" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="code" label="商品编码" min-width="120" align="center"/>
        <el-table-column prop="name" label="商品名称" min-width="160" align="center"/>
        <el-table-column prop="unit" label="单位" width="100" align="center"/>
        <el-table-column prop="quantity" label="数量" width="120" align="center"/>
        <el-table-column prop="unitPrice" label="单价(¥)" width="120" align="center">
          <template #default="{ row }">{{ formatMoney(row.unitPrice) }}</template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="小计(¥)" width="140" align="center">
          <template #default="{ row }">{{ formatMoney(row.totalPrice) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row, $index }">
            <el-button size="small" type="primary" @click="editItem(row, $index)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeItem($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="PurchaseRegister-table-summary">
        <div class="PurchaseRegister-table-summary-row">
          <div class="PurchaseRegister-table-summary-label">合计金额：</div>
          <div class="PurchaseRegister-table-summary-value">¥ {{ formatMoney(totalAmount) }}</div>
        </div>
      </div>
    </div>

    <!-- 保存操作栏（列表外层，下方） -->
    <div class="PurchaseRegister-actions">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>

    <!-- 商品选择弹窗 -->
    <ProductSelectDialog v-model:visible="selectDialogVisible" @selected="handleProductSelected"/>
    <!-- 采购填写弹窗：支持传入 productId 或 product 对象 -->
    <ProductItemDialog
        v-model:visible="itemDialogVisible"
        :product-id="currentProductId"
        :product="currentProduct"
        :initial="currentItemInitial"
        mode="purchase"
        @confirm="handleItemConfirm"
    />
    <!-- 保存确认弹窗 -->
    <PurchaseSaveConfirmDialog
        v-model:visible="saveConfirmVisible"
        :info="saveInfo"
        :items="items"
        @confirm="handleSaveConfirm"
    />
  </div>
</template>

<script setup>
import {computed, reactive, ref, onMounted, watch} from 'vue'
import {ElMessage} from "element-plus";
import ProductSelectDialog from "../../../../components/ProductSelectDialog.vue";
import ProductItemDialog from "../.././components/ProductItemDialog.vue";
import PurchaseSaveConfirmDialog from "./PurchaseSaveConfirmDialog.vue";
import {listSuppliers} from "../../../../api/supplierApi.js";
import {addPurchaseOrder} from "../../../../api/purchaseOrderApi.js";

// 采购单基本信息
const formRef = ref()
const form = reactive({
  orderNo: '',
  supplierId: null,
  orderDate: '',
  note: '',
  items: [],
  totalAmount: 0 // 新增：总价
})

// 供应商列表
const supplierList = ref([])

// 表单校验规则
const rules = reactive({
  orderNo: [{required: true, message: '请输入订单编号', trigger: 'blur'}],
  supplierId: [{required: true, message: '请选择供应商', trigger: 'change'}],
  orderDate: [{required: true, message: '请选择日期', trigger: 'change'}]
})

// 已添加商品列表
const items = ref([])
// 将商品列表同步到表单对象，确保保存时包含
watch(items, (val) => {
  // 浅拷贝一份，避免与表格列表共享引用
  form.items = val.map(i => ({ ...i }))
}, { deep: true, immediate: true })

const totalAmount = computed(() => items.value.reduce((acc, cur) => acc + Number(cur.totalPrice || 0), 0))
// 同步总价到表单
watch(totalAmount, (v) => {
  form.totalAmount = Number(v || 0)
}, { immediate: true })

// 弹窗状态及当前操作商品
const selectDialogVisible = ref(false)
const itemDialogVisible = ref(false)
const saveConfirmVisible = ref(false)
const currentProduct = ref(null) // 编辑时使用
const currentProductId = ref(null) // 新增时传递ID
const currentEditIndex = ref(-1)
const currentItemInitial = ref(null)

// 生成随机订单编号
const generateOrderNo = () => {
  const randomCode = Math.floor(Math.random() * 100000000).toString().padStart(8, '0')
  form.orderNo = randomCode
  ElMessage.success('已生成随机编码: ' + randomCode)
}

// 设置系统时间（只读显示）
const formatDate = (d) => {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

// 打开商品选择弹窗
const openSelectProduct = () => {
  selectDialogVisible.value = true
}

// 处理商品选择结果（仅传递ID）
const handleProductSelected = (product) => {
  selectDialogVisible.value = false
  if (!product) return
  currentProduct.value = null
  currentProductId.value = product.id
  currentItemInitial.value = null
  currentEditIndex.value = -1
  itemDialogVisible.value = true
}

// 处理商品填写结果
const handleItemConfirm = (payload) => {
  if (currentEditIndex.value >= 0) {
    items.value.splice(currentEditIndex.value, 1, payload)
  } else {
    items.value.push(payload)
  }
  itemDialogVisible.value = false
}

// 编辑已添加商品（继续传对象）
const editItem = (row, index) => {
  currentProductId.value = null
  currentProduct.value = {id: row.productId, code: row.code, name: row.name, unit: row.unit}
  currentItemInitial.value = {
    quantity: row.quantity,
    unitPrice: row.unitPrice,
    totalPrice: row.totalPrice,
    priceMode: row.priceMode || 'unit'
  }
  currentEditIndex.value = index
  itemDialogVisible.value = true
}

// 删除已添加商品
const removeItem = (index) => {
  items.value.splice(index, 1)
}

// 重置表单和商品列表
const handleReset = () => {
  form.orderNo = ''
  form.supplierId = null
  form.orderDate = formatDate(new Date()) // 重置为系统时间
  form.note = ''
  items.value = []
  form.items = []
  form.totalAmount = 0
}

// 供应商名称
const supplierName = computed(() => {
  const s = supplierList.value.find(i => i.id === form.supplierId)
  return s ? s.name : ''
})

// 保存确认弹窗展示信息（携带总价）
const saveInfo = computed(() => ({
  orderNo: form.orderNo,
  supplierId: form.supplierId,
  supplierName: supplierName.value,
  orderDate: form.orderDate,
  note: form.note,
  totalAmount: form.totalAmount
}))

// 提交表单 => 打开确认弹窗
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    saveConfirmVisible.value = true
  } catch (e) {
    console.error(e)
  }
}

// 确认保存（暂不实现接口调用，仅占位并关闭弹窗）
const handleSaveConfirm = async () => {
  // 这里可后续接入保存接口
  saveConfirmVisible.value = false
  await addPurchaseOrder(form).then((res) => {
    if (res) {
      ElMessage.success('采购单已保存')
      handleReset()
    }
  })
}

// 金额格式化
const formatMoney = (v) => Number(v || 0).toFixed(2)

// 加载数据
const loadSuppliers = () => {
  listSuppliers({condition: {}}).then((res) => {
    supplierList.value = res.list || []
  }).catch((err) => {
    console.error('获取供应商列表失败:', err)
    ElMessage.error('获取供应商列表失败')
  })
}

// 初始化加载
onMounted(() => {
  loadSuppliers()
  form.orderDate = formatDate(new Date())
})
</script>

<style scoped lang="scss">
.PurchaseRegister {
  &-form {
    padding: 16px 0;

    &-orderNo {
      display: flex;
      align-items: center;
      gap: 8px;

      &-input {
        flex: 1;
      }

      &-btn {
        flex: 0 0 auto;
        white-space: nowrap;
      }
    }

    &-input {
      width: 100%;
    }
  }

  &-table {
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-toolbar {
      display: flex;
      gap: 8px;
      padding: 16px 0;
      border-bottom: 1px solid #eee;
    }

    &-main {
      width: 100%;
    }

    &-summary {
      display: flex;
      justify-content: flex-end;
      padding: 16px 0;

      &-row {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      &-label {
        font-size: 14px;
        color: #606266;
      }

      &-value {
        font-size: 16px;
        color: #303133;
        font-weight: 600;
      }
    }
  }

  &-actions {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;
    border-top: 1px solid #eee; /* 与列表之间的分割线 */
  }
}
</style>
